<template>
    <div class="wrap normal">
        <!-- 搜索条件 -->
        <div class="wrap-form" id="wrap-form">
            <el-row>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <div class="left-panel">
                        <el-form :inline="true" :model="form" label-width="80px" @submit.native.prevent>
                            <el-form-item>
                                <el-input v-model="form.name" placeholder="请输入角色名称" clearable style="width: 220px"></el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" icon="el-icon-search" @click="pageOperate('search')">搜索</el-button>
                                <el-button type="primary" icon="el-icon-plus" @click="pageOperate('add')" v-hasPerm="'system:roleManage:add'">添加</el-button>
                                <el-button icon="el-icon-refresh" @click="pageOperate('refresh')">刷新</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-col>
            </el-row>
        </div>
        <!-- table数据 -->
        <el-row :gutter="20">
            <el-col :span="16">
                <div class="wrap-table">
                    <el-table ref="singleTable" :data="tableData" :max-height="tableMaxHeight" border v-loading="tableLoading" :header-cell-style="{ background: '#F5F6FA' }" @sort-change="tableSortChange" highlight-current-row @row-click="rowClick">
                        <el-table-column type="index" label="序号" width="50" align="center"> </el-table-column>
                        <el-table-column prop="name" label="角色名称" min-width="100"> </el-table-column>
                        <el-table-column prop="code" label="角色标识" min-width="100"> </el-table-column>
                        <el-table-column prop="remark" label="备注" min-width="100" show-overflow-tooltip> </el-table-column>
                        <el-table-column label="状态" min-width="100">
                            <template slot-scope="scope">
                                <el-tag :type="$options.filters.filterStatusClass(scope.row.status)">{{ scope.row.status | filterStatus }}</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="sort" label="排序" min-width="60" sortable="custom"> </el-table-column>
                        <el-table-column label="操作" width="100" fixed="right">
                            <template slot-scope="scope">
                                <el-button type="text" v-hasPerm="'system:roleManage:edit'" @click.stop="pageOperate('edit', scope.row)">修改</el-button>
                                <el-button type="text" v-hasPerm="'system:roleManage:delete'" @click.stop="pageOperate('deleteOne', scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination :total="page.totalNum" :page.sync="page.pageNum" :limit.sync="page.pageSize" layout="total, sizes, prev, pager, next, jumper" @pagination="getTableData" />
                </div>
            </el-col>
            <el-col :span="8">
                <div class="wrap-setting" v-loading="settingLoading">
                    <div class="setting-head">
                        <p class="head-title">菜单分配</p>
                        <el-button type="primary" v-hasPerm="'system:roleManage:perm'" :loading="operateLoading" @click="pageOperate('savePerm')">保存</el-button>
                    </div>
                    <div class="setting-content">
                        <el-checkbox-group v-model="menuConfigList">
                            <el-checkbox label="1">展开/折叠</el-checkbox>
                            <el-checkbox label="2">全选/取消</el-checkbox>
                            <el-checkbox label="3">父子联动</el-checkbox>
                        </el-checkbox-group>
                        <el-tree class="content-tree" ref="tree" :data="menuList" node-key="id" show-checkbox check-on-click-node :default-expand-all="isExpand" :check-strictly="!isStrictly" :expand-on-click-node="false" :default-checked-keys="operateForm.menuIds" :props="{ children: 'children', label: 'name' }"> </el-tree>
                    </div>
                </div>
            </el-col>
        </el-row>
        <!-- 新增/编辑角色 -->
        <el-dialog v-if="operateDialog" :title="operateTitle" :visible.sync="operateDialog" @close="closeOperateDialog" :width="`${operateWidth}px`" :close-on-press-escape="false" :close-on-click-modal="false">
            <template v-if="operateType === 'add' || operateType === 'edit'">
                <el-form ref="operateForm" :model="operateForm" :rules="operateRules" label-width="100px">
                    <el-form-item label="角色名称" prop="name">
                        <el-input v-model="operateForm.name" clearable placeholder="请输入角色名称"></el-input>
                    </el-form-item>
                    <el-form-item label="角色标识" prop="code">
                        <el-input v-model="operateForm.code" clearable placeholder="请输入角色标识"></el-input>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="operateForm.remark" clearable type="textarea" :rows="3" placeholder="请输入备注"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-radio-group v-model="operateForm.status">
                            <el-radio v-for="(item, index) in statusOptions" :label="item.value" :key="index">{{ item.label }}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input-number v-model="operateForm.sort" size="small" :min="0" />
                    </el-form-item>
                </el-form>
            </template>
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeOperateDialog">取 消</el-button>
                <el-button type="primary" :loading="operateLoading" @click="operateSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { treeToArray } from '@/utils'
import tableHeight from '@/mixins/tableHeight'
import { statusOptions } from '@/filters/options'
import { getRoleManageList, addOrUpdateRole, getRoleMenuById, postRolePerms, deleteRole, getMenuList } from '@/api/system'
export default {
    name: 'RoleManage',
    mixins: [tableHeight],
    computed: {
        // 是否展开
        isExpand() {
            return this.menuConfigList.some(item => item === '1')
        },
        // 是否全选
        isSelectAll() {
            return this.menuConfigList.some(item => item === '2')
        },
        // 是否联动
        isStrictly() {
            return this.menuConfigList.some(item => item === '3')
        }
    },
    data() {
        return {
            // 搜索条件
            form: {
                name: '',
                fieldSort: '',
                orderSort: ''
            },
            // 分页
            page: {
                pageNum: 1,
                pageSize: 10,
                totalNum: 0
            },
            // 列表加载
            tableLoading: false,
            // 列表
            tableData: [],
            // 操作类型
            operateType: '',
            // 宽度
            operateWidth: 550,
            // 操作标题
            operateTitle: '',
            // 操作dialog
            operateDialog: false,
            // 操作确认按钮loading
            operateLoading: false,
            // 菜单权限选择配置
            menuConfigList: [],
            // 操作form
            operateForm: {
                id: '',
                name: '',
                code: '',
                remark: '',
                status: 0,
                sort: 1,
                // 当前行id
                rowId: '',
                menuIds: [] //选中的权限菜单
            },
            // 操作表单校验规则
            operateRules: {
                name: [
                    { required: true, message: '请输入角色名称', trigger: ['blur'] }
                ],
                code: [
                    { required: true, message: '请输入角色标识', trigger: ['blur'] }
                ],
                status: [
                    { required: true, message: '请选择状态', trigger: ['blur', 'change'] }
                ],
                sort: [
                    { required: true, message: '请输入排序', trigger: ['change'] }
                ],
            },
            // 菜单列表 - 选择菜单权限
            menuList: [],
            // 状态
            statusOptions,
            // 选中行
            currentRow: null,
            // 菜单分配加载
            settingLoading: false
        }
    },
    methods: {
        // 点击行
        rowClick(row) {
            if (this.currentRow && this.currentRow.id === row.id) {
                this.currentRow = null
                this.$refs.singleTable.setCurrentRow();
                // 切换权限菜单
                this.$refs.tree.setCheckedKeys([])
                this.menuConfigList = []
            } else {
                this.currentRow = row
                this.$refs.singleTable.setCurrentRow(row);
                // 切换权限菜单
                this.pageOperate('perm', row)
                this.menuConfigList = []
            }
        },
        // 排序
        tableSortChange(data) {
            this.form.fieldSort = data.prop
            this.form.orderSort = data.order
            this.getTableData()
        },
        // 数据
        getTableData() {
            this.tableLoading = true
            const data = {
                pageNum: this.page.pageNum,
                pageSize: this.page.pageSize,
                ...this.form
            }
            getRoleManageList(data).then(res => {
                this.tableLoading = false
                this.tableData = res.data.records
                this.page.totalNum = res.data.total
            }).catch(error => {
                this.tableLoading = false
            })
        },
        // 操作
        pageOperate(type, row) {
            this.operateType = type
            switch (type) {
                case 'search':
                    this.page.pageNum = 1
                    this.getTableData()
                    break;
                case 'refresh':
                    Object.assign(this.$data, this.$options.data())
                    this.getTableData()
                    this.initMenuOptions()
                    break;
                case 'add':
                    this.operateDialog = true
                    this.operateTitle = '新增角色'
                    break;
                case 'edit':
                    this.operateDialog = true
                    this.operateTitle = '修改角色'
                    for (let key in this.operateForm) {
                        this.operateForm[key] = row[key]
                    }
                    break;
                case 'deleteOne':
                    this.$confirm('确认删除此角色?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        deleteRole(row.id).then(res => {
                            this.getTableData()
                            this.$message_tip(`删除成功`, 'success')
                            // 重置选中过的行
                            this.currentRow = null
                            // 重置权限菜单
                            this.$refs.tree.setCheckedKeys([])
                        }).catch(error => { })
                    }).catch(() => { });
                    break;
                case 'perm':
                    this.operateForm.rowId = row.id
                    this.settingLoading = true
                    // 查询角色权限
                    getRoleMenuById({
                        roleId: row.id
                    }).then(res => {
                        this.operateForm.menuIds = res.data
                        this.$refs.tree.setCheckedKeys(res.data)
                        this.menuConfigList = ['3']
                        this.settingLoading = false
                    }).catch(error => {
                        this.settingLoading = false
                    })
                    break;
                case 'savePerm':
                    // 全选的id
                    let keysList = this.$refs.tree.getCheckedKeys()
                    // 未全选子的父id
                    let halfCheckedList = this.$refs.tree.getHalfCheckedKeys()
                    let selectKeyList = keysList.concat(halfCheckedList)
                    if (selectKeyList.length <= 0) return this.$message_tip('请选择菜单权限', 'error')
                    this.operateLoading = true
                    postRolePerms({
                        id: this.operateForm.rowId,
                        menuIds: selectKeyList
                    }).then(res => {
                        this.getTableData()
                        this.$message_tip('菜单分配成功', 'success')
                        this.operateLoading = false
                        // 重置选中过的行
                        this.currentRow = null
                        // 重置权限菜单
                        this.$refs.tree.setCheckedKeys([])
                    }).catch(error => {
                        this.operateLoading = false
                    })
                    break;
                default:
                    break;
            }
        },
        // 提交
        operateSubmit() {
            this.$refs.operateForm.validate(valid => {
                if (valid) {
                    if (this.operateType === 'add' || this.operateType === 'edit') {
                        // 表单数据
                        let formData = JSON.parse(JSON.stringify(this.operateForm))
                        delete formData.menuIds
                        delete formData.rowId
                        this.operateLoading = true
                        addOrUpdateRole(formData).then(res => {
                            this.getTableData()
                            this.$message_tip(`${this.operateTitle}成功`, 'success')
                            this.closeOperateDialog()
                        }).catch(error => {
                            this.operateLoading = false
                        })
                    }
                }
            })
        },
        // 关闭操作按钮
        closeOperateDialog() {
            this.operateLoading = false
            this.operateDialog = false
            this.operateType = ''
            this.operateTitle = ''
            this.operateForm = this.$options.data().operateForm
            // 重置选中过的行
            this.currentRow = null
            // 重置权限菜单
            this.$refs.tree.setCheckedKeys([])
        },
        // 获取可分配的权限菜单
        initMenuOptions() {
            getMenuList({}).then(res => {
                this.menuList = res.data
            }).catch(error => { })
        }
    },
    mounted() {
        this.getTableData()
        this.initMenuOptions()
    },
    watch: {
        'isExpand': function (newVal, oldVal) {
            for (let i = 0; i < this.$refs.tree.store._getAllNodes().length; i++) {
                this.$refs.tree.store._getAllNodes()[i].expanded = this.isExpand
            }
        },
        'isSelectAll': function (newVal, oldVal) {
            if (newVal) {
                let list = treeToArray(this.menuList)
                this.$refs.tree.setCheckedKeys(list.map(item => item.id))
            } else {
                this.$refs.tree.setCheckedKeys([])
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.wrap-setting {
    border: 1px solid #e6e6e6;
    .setting-head {
        height: 50px;
        padding: 0 15px;
        border-bottom: 1px solid #e6e6e6;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .head-title {
            font-size: 14px;
            font-weight: 400;
            color: #141222;
        }
    }
    .setting-content {
        min-height: 100px;
        padding: 15px;
        .content-tree {
            margin-top: 10px;
        }
    }
}
</style>
